/*
 * Powered By xTOOLs
 * Dev by DuRisk@pactera.com
 * Copyright © 2009 - 2017 pactera.com. All rights reserved.
 *
 * Generated at 2017年12月25日 10:52:48
 *
 */

package com.pactera.jep.service.sys.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.sys.model.MetaRegion;
import com.pactera.jep.sys.model.MetaTable;
import com.pactera.jep.sys.service.MetaRegionService;
import com.pactera.jep.sys.service.MetaTableService;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.entity.BasicNameValuePair;
import com.pactera.jep.web.entity.NameValuePair;
import com.pactera.jep.web.util.RequestUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="元数据table管理")
@RestController
@RequestMapping("/metaTable")
public class MetaTablerRestController extends BaseRestController<MetaTable> {
	private static Logger	logger	= LoggerFactory.getLogger(MetaTablerRestController.class);

	@Autowired
	private MetaTableService	metaTableService;
	
	@Autowired
	private MetaRegionService	metaRegionService;

	
	/**
	 * 分页查询
	 * @param page
	 * @param model
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "分页查询元数据的table表")
	@GetMapping(value = "/queryMetatable")
	public Map<String, Object> queryMetatable(Page<MetaTable> page, Model model, HttpServletRequest request)
	{
		Map<String, Object> result = new HashMap<String, Object>();
		List<Filter> filters = RequestUtils.buildFilters(request);
		List<Order> orders = RequestUtils.buildOrders(request);
		metaTableService.queryMetatable(page, filters, orders);
		result.put(RESULT_TOTAL, page.getTotal());
		result.put(RESULT_ROWS, page.getResult());
		return result;
	}
	
	/**
	 * 分页查询
	 * @param page
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = {"/queryMetatableNoPage"}, produces = {"application/json;charset=UTF-8"}, method = {RequestMethod.GET})
	@ResponseBody
	public Map<String, Object> queryMetatableNoPage(Model model, HttpServletRequest request)
	{
		Map<String, Object> result = new HashMap<String, Object>();
		List<Filter> filters = RequestUtils.buildFilters(request);
		List<Order> orders = RequestUtils.buildOrders(request);
		List<MetaTable> metaTables = metaTableService.selectMetatable(filters, orders);
		result.put(RESULT_TOTAL, metaTables.size());
		result.put(RESULT_ROWS, metaTables);
		return result;
	}
	/*
	  分页查询
	  @param page
	  @param model
	  @param request
	  @return*/

	@ApiOperation(value = "同步模态框根据tableCodes分页查询table表")
	@PostMapping(value = "/queryTables")
	public Map<String, Object> queryTables(@RequestBody JSONObject params)
	{
		String schema = params.getString("schema");
		String tableCodes = params.getString("tableCodes");
		Map<String, Object> result = new HashMap<String, Object>();
		List<MetaTable> metaTables = metaTableService.selectTables(schema, tableCodes);
		result.put(RESULT_ROWS, metaTables);
		result.put(RESULT_TOTAL, metaTables.size());
		return result;
	}


	/**
	 * 为列表页面做数据准备
	 */
	@Override
	protected void prepareQuery(@ApiIgnore @RequestHeader("x-user-token") String token
			,Page<MetaTable> page, List<Filter> filters, List<Order> orders,HttpServletRequest request) {
		
		metaTableService.query(page, filters, orders);
	}

	

	/**
	 * 保存
	 * @param metaTable
	 * @return
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public Map<String, Object> save(MetaTable metaTable) {
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		Boolean isExist = metaTableService.exists(metaTable.getTableId());
		try 
		{
			if(isExist)
			{
				
				metaTableService.update(metaTable);
			}
			else
			{
				metaTableService.insert(metaTable);
			}
			
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		}
		catch (ServiceException e) 
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		return tips;
	}
	
	/**
	 * 删除
	 * @param tableId
	 * @return
	 */
	@ApiOperation(value = "删除元数据表和元数据字段")
	@PostMapping(value = "/remove")
	public Map<String, Object> remove(@RequestBody JSONObject jsonObject, boolean isDel){

		String regionId = jsonObject.getString("regionId");
		String tableId = jsonObject.getString("tableId");
		Map<String, Object> tips = new HashMap<String, Object>();
		
		try 
		{
			/* 删除元数据表和元数据字段，先删除字段，再删除表 */
			metaTableService.delMetaTableAndDBObject(regionId, tableId, isDel);
			if(!isDel){
				Long metaRegionTableCount = metaTableService.countTableByTableId(tableId);
				tips.put("tableCount", metaRegionTableCount);
			}
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_DELETE);
		} 
		catch (ServiceException e) 
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_DELETE);
		}
		
		return tips;
	}
	
	/**
	 * 验证提交的tableId是否已经存在数据库中
	 * @param tableId
	 * @return
	 */
	@RequestMapping(value = "/check", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> check(String tableId){
		
		Map<String, Object> tips = new HashMap<String, Object>();
		
		boolean exist = metaTableService.exists(tableId);
		tips.put("valid", !exist);
		
		return tips;
	}
	
	/**
	 * 查询表字段
	 * @return 表字段
	 */
	@ApiOperation(value = "查询表字段")
	@GetMapping(value = "/querySchema")
	public List<NameValuePair> querySchema(){
		List<String> schemas = metaTableService.querySchema();
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		for(String schema : schemas){
			nameValuePairs.add(new BasicNameValuePair(schema, schema));
		}
		return nameValuePairs;
	}

	/*@ApiOperation(value = "同步数据")
	@PostMapping(value = "/syncCheckMetaTable")
	public Map<String , Object> syncCheckMetaTable(String  mts, String mId){
		Map<String, Object> tips = new HashMap<String, Object>();
		try {
			*//*判断传过来的元数据表是否为空*//*
			if(!StringUtils.isBlank(mts))
			{
				*//* 同步元数据表 *//*
				metaTableService.syncCheckMetaTable(mts, mId);
			}
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_OPERATE);
		} catch (Exception e) {
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_OPERATE);
		}
		return tips;
	}*/
	@ApiOperation(value = "同步数据")
	@PostMapping(value = "/syncCheckMetaTable")
	public Map<String , Object> syncCheckMetaTable(@RequestBody JSONObject jsonObject){
		String mts = jsonObject.getString("mts");
		String mId = jsonObject.getString("mId");
		Map<String, Object> tips = new HashMap<String, Object>();
		try {
			/*判断传过来的元数据表是否为空*/
			if(!StringUtils.isBlank(mts))
			{
				/* 同步元数据表 */
				metaTableService.syncCheckMetaTable(mts, mId);
			}
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_OPERATE);
		} catch (Exception e) {
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_OPERATE);
		}
		return tips;
	}
	
	/**
	 * 分页查询
	 * @param page
	 * @param model
	 * @param request
	 * @return
	 */
	@ApiOperation("获得所有列表数据")
	@GetMapping(
			value = {"/queryMetatableExclude"},
			produces = {"application/json;charset=UTF-8"}
	)
	public Map<String, Object> queryMetatableExclude(@ApiIgnore @RequestHeader("x-user-token") String token, Page<MetaTable> page, Model model, HttpServletRequest request)
	{
		Map<String, Object> result = new HashMap<String, Object>();
		List<Filter> filters = RequestUtils.buildFilters(request);
		List<Order> orders = RequestUtils.buildOrders(request);
		metaTableService.queryMetatable(page, filters, orders);
		result.put(RESULT_TOTAL, page.getTotal());
		result.put(RESULT_ROWS, page.getResult());
		return result;
	}
	
	/**
	 * 导出数据区域下面所有数据
	 * @param request
	 * @param response
	 * @param regionId
	 */
	@ApiOperation(value = "导出数据区域下面所有数据")
	@PostMapping(value = "/exportAll")
	public void exportAll(@RequestBody JSONObject json, HttpServletRequest request, HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");  
		response.setContentType("application/x-msdownload;");  
		BufferedOutputStream bos = null; 
		try {

			String regionId = json.getString("regionId");

			/*查询regionCode*/
			MetaRegion metaRegion = metaRegionService.get(regionId);
			String fileName = metaRegion.getRegionCode() + ".xlsx";
			
			/*查询导出的数据*/
			byte[] outBody = metaTableService.toXlsDataAll(regionId, fileName, metaRegion);
			
		
			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			
			response.setHeader("Content-Length", String.valueOf(outBody.length));
			bos = new BufferedOutputStream(response.getOutputStream());
			bos.write(outBody, 0, outBody.length);
		} catch (IOException e) {
			logger.error("下载失败：" + e.getMessage());
		} finally {  
			try {
				if (bos != null)  
					bos.close();  
			} catch (IOException e) {
				logger.error("关闭IO流缓冲失败：" + e.getMessage());
			}  
        }
	}
}